#include "statisticalwidget.h"
#include "databasemanager.h"
#include "ui_statisticalwidget.h"
#include "dataexporter.h"

#include <QSqlQuery>
#include <QTimer>
#include <QSqlQueryModel>
#include <QAbstractTableModel>

StatisticalWidget::StatisticalWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::StatisticalWidget)
{
    ui->setupUi(this);


    //================ 动态UI配置 ================//
    QTableView *tableView = ui->tableView;
    // 列宽设置（可随窗口大小调整）
    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);


    // 样式配置（可动态修改）
    tableView->setAlternatingRowColors(true); // 交替颜色起用

    // 表头样式
    tableView->verticalHeader()->setDefaultSectionSize(70);
    tableView->horizontalHeader()->setMinimumHeight(50);
    tableView->horizontalHeader()->setStyleSheet("font-size:16pt;");

    // 设置选择模式和行为
    tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);  // 多选  QAbstractItemView::ContiguousSelection
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);  // 选中整行
    tableView->setEditTriggers(QAbstractItemView::DoubleClicked);// | QAbstractItemView::SelectedClicked

    mySkin[0] = {QColor(252,77,62),QColor(21,23,49),QColor(200,29,14),"252,77,62","21,23,49"};              //商务
    mySkin[1] = {QColor(49,177,72),QColor(26,142,199),QColor(61,222,85),"49,177,72","26,142,199"};          //夏日
    mySkin[2] = {QColor(138,103,205),QColor(137,204,208),QColor(122,64,232),"138,103,205","137,204,208"};   //清晰
    mySkin[3] = {QColor(252,53,152),QColor(83,207,199),QColor(200,30,114),"252,53,152","83,207,199"};       //猛男
    curr_skin = 0;


    pie_init();         //饼状图初始化
    bar_init();         //柱状图初始化

    //定时器初始化
    // time_run = new QTimer(this);
    // connect(time_run,SIGNAL(timeout()),this,SLOT(slot_pie_roll()));
    // connect(time_run,SIGNAL(timeout()),this,SLOT(slot_bar_roll()));
    // time_run->start(500);

    // 初始化为当前系统时间
    ui->dateEdit_atten->setDate(QDate::currentDate());


    // 查询模型初始化
    m_statisticalModel = new QSqlQueryModel(this);

}

StatisticalWidget::~StatisticalWidget()
{
    delete ui;
}


void StatisticalWidget::on_btn_export_clicked()
{
    // 获取视图关联的模型
    QSqlQueryModel *model = qobject_cast<QSqlQueryModel*>(ui->tableView->model());
    if (!model) {
        QMessageBox::critical(this, "错误", "当前视图的模型不是QSqlQueryModel类型");
        return;
    }

    QString savePath = QFileDialog::getSaveFileName(this,
                                                    "保存CSV",
                                                    QDir::homePath(),
                                                    "CSV文件 (*.csv)");

    if (!savePath.isEmpty()) {
        if (DataExporter::exportToCsv(model, savePath)) {
            QMessageBox::information(this, "导出成功", "CSV文件已生成");
        } else {
            QMessageBox::critical(this, "错误", DataExporter::lastError());
        }
    }
}


void StatisticalWidget::do_updateStatiscalView(QSqlQuery query)
{
    QSqlQueryModel *model = m_statisticalModel;
    model->setQuery(query);
    ui->tableView->setModel(model);
}

void StatisticalWidget::do_updateStatiscalChart(QSqlQuery query)
{
    qDebug() << "do_updateStatiscalChart 信号接收";
    // 标题
    QString currentDeptName = ui->cBox_attenTable->currentText();
    QString Title = "部门出勤率";
    QDate currentDate = QDate::currentDate();
    if("日考勤表" == currentDeptName) {
        Title += currentDate.toString("(yyyy-MM-dd)");
    } else if("周考勤表" == currentDeptName){
        int year = 0;
        int weekNumber = currentDate.weekNumber(&year);
        Title += currentDate.toString(" (yyyy)") +
                 QString(" 第%1周").arg(weekNumber);
    } else if("月考勤表" == currentDeptName){
        Title += QDate::currentDate().toString("(yyyy-MM)");
    }
#if 1
    // 数据集合
    QMap<QString, double> deptMap;

    while(query.next()) {
        // 添加数据
        deptMap.insert(query.value("dept_name").toString(), // 部门名
                       query.value("rate").toDouble()); // 出勤率
    };

    // qDebug() << "数据集合:" << deptMap;
#endif
    // 更新图表
    do_bar_roll(Title, deptMap);
    do_pie_roll(Title, deptMap);

}

void StatisticalWidget::do_updateDeptCoboxCom(QStringList &deptNames)
{
    QString currentDept = ui->cBox_depts->currentText();
    // 更新部门表下拉框
    QStringList items = deptNames;
    items.append("所有部门");
    QStringList uniqueList = items.toSet().toList();
    uniqueList.sort(Qt::CaseInsensitive); // 按字母排序
    ui->cBox_depts->clear();
    ui->cBox_depts->addItems(uniqueList);
    ui->cBox_depts->setCurrentText(currentDept);

}


void StatisticalWidget::on_btn_update_clicked()
{
    QString timeRange = ui->cBox_attenTable->currentText();
    QString deptName = ui->cBox_depts->currentText();
    QString status = ui->cBox_attenType->currentText();
    QDate date = ui->dateEdit_atten->date();

    // 发送查询数据信号
    emit queryStatistical(timeRange, deptName, status, date);
}

